<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="82px">
         <el-form-item label="联系人名称" prop="contactsName">
            <el-input v-model="queryParams.contactsName" placeholder="请输入联系人名称" clearable style="width: 240px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="联系电话" prop="phonenumber">
            <el-input v-model="queryParams.phonenumber" placeholder="请输入联系电话" clearable style="width: 240px"
               maxlength="11" @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="钉钉号" prop="dingding">
            <el-input v-model="queryParams.dingding" placeholder="请输入钉钉号" clearable style="width: 240px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="邮箱" prop="email">
            <el-input v-model="queryParams.email" placeholder="请输入邮箱" clearable style="width: 240px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="联系人状态" clearable style="width: 240px">
               <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item label="单位" prop="companyId">
            <el-select v-model="queryParams.companyId" placeholder="请选择单位" style="width: 240px"
               @keyup.enter="handleQuery">
               <el-option v-for="item in options" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
            </el-select>
         </el-form-item>
         <el-form-item label="部门" prop="deptId">
            <el-tree-select v-model="queryParams.deptId" :data="deptOptions"
               :props="{ label: 'label', children: 'children' }" node-key="id" :check-strictly="true"
               placeholder="请选择部门" :render-after-expand="false" style="width: 240px" @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
               start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['contact:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
               v-hasPermi="['contact:edit']">修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
               v-hasPermi="['contact:remove']">删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
               v-hasPermi="['contact:export']">导出</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="联系人编号" align="center" prop="id" width="120" />
         <el-table-column label="联系人名称" align="center" prop="contactsName" :show-overflow-tooltip="true" />
         <el-table-column label="联系电话" align="center" prop="phonenumber" :show-overflow-tooltip="true" />
         <el-table-column label="钉钉号" align="center" prop="dingding" :show-overflow-tooltip="true" />
         <el-table-column label="邮箱" align="center" prop="email" :show-overflow-tooltip="true" />
         <el-table-column label="单位" align="center" prop="companyId" :show-overflow-tooltip="true" >
            <template #default="scope">
              {{ options.find(item => item.deptId === scope.row.companyId)?.deptName }}
            </template>
         </el-table-column>
         <el-table-column label="部门" align="center" prop="deptId" :show-overflow-tooltip="true" >
            <template #default="scope">
              {{ findLabelInTree(deptOptions, scope.row.deptId) }}
            </template>
         </el-table-column>
         <el-table-column label="状态" align="center" width="60">
            <template #default="scope">
               <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                  @change="handleStatusChange(scope.row)"></el-switch>
            </template>
         </el-table-column>
         <el-table-column label="创建时间" align="center" prop="createTime" width="150">
            <template #default="scope">
               <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
            <template #default="scope">
               <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['contact:edit']"></el-button>
               </el-tooltip>
               <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['contact:remove']"></el-button>
               </el-tooltip>
            </template>
         </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize" @pagination="getList" />

      <!-- 添加或修改联系人配置对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
         <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="联系人名称" prop="contactsName">
               <el-input v-model="form.contactsName" placeholder="请输入联系人名称" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phonenumber">
               <el-input v-model="form.phonenumber" controls-position="right" maxlength="11" />
            </el-form-item>
            <el-form-item label="钉钉号" prop="dingding">
               <el-input v-model="form.dingding" controls-position="right" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
               <el-input v-model="form.email" controls-position="right" />
            </el-form-item>
            <el-form-item label="单位" prop="companyId">
               <el-select v-model="form.companyId" placeholder="请选择单位" controls-position="right">
                  <el-option v-for="item in options" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
               </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
               <el-tree-select v-model="form.deptId" :data="deptOptions"
                  :props="{ label: 'label', children: 'children' }" node-key="id" :check-strictly="true"
                  placeholder="请选择部门" :render-after-expand="false" controls-position="right" />
            </el-form-item>
            <el-form-item label="状态">
               <el-radio-group v-model="form.status">
                  <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label
                     }}</el-radio>
               </el-radio-group>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>

   </div>
</template>

<script setup name="contact">
import { deptTreeSelect } from "@/api/system/user"
import { getBoss } from "@/api/system/dept"
import { addContact, listContact, delContact, updateContact, getContact, statusContact } from "@/api/contact";
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const options = ref([])
const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const menuRef = ref(null);
const deptOptions = ref(undefined);
const data = reactive({
   form: {},
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      roleName: undefined,
      roleKey: undefined,
      status: undefined
   },
   rules: {
      contactsName: [{ required: true, message: "联系人名称不能为空", trigger: "blur" }],
      phonenumber: [{ required: true, message: "联系方式不能为空", trigger: "blur" }],
   },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询部门下拉树结构 && 查询单位下拉选择 */
function getDeptTree() {
   deptTreeSelect().then(response => {
      deptOptions.value = response.data;
   });
   getBoss().then(response => {
      options.value = response.data
   })
};

/** 查询联系人列表 */
function getList() {
   loading.value = true;
   if (dateRange.value && dateRange.value.length > 0) {
      queryParams.value.createTimeStart = dateRange.value[0]
      queryParams.value.createTimeEnd = dateRange.value[1]
   } else {
      queryParams.value.createTimeStart = undefined
      queryParams.value.createTimeEnd = undefined
   }
   listContact(proxy.addDateRange(queryParams.value)).then(response => {
      roleList.value = response?.data?.rows;
      total.value = response?.data?.total;
      loading.value = false;
   });
}
/** 递归查找树形结构中某个节点的 label */
function findLabelInTree(tree, id) {
    for (const node of tree) {
      // 如果当前节点的 id 匹配，返回其 label
      if (node.id === id) {
        return node.label;
      }
      // 如果当前节点有子节点，递归查找子节点
      if (node.children && node.children.length > 0) {
        const result = this.findLabelInTree(node.children, id);
        if (result) {
          return result;
        }
      }
    }
    // 如果未找到，返回默认值
    return '';
  }

/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
}

/** 重置按钮操作 */
function resetQuery() {
   dateRange.value = [];
   queryParams.value.createTimeStart = undefined
   queryParams.value.createTimeEnd = undefined
   proxy.resetForm("queryRef");
   handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
   const Ids = row.id || ids.value;
   proxy.$modal.confirm('是否确认删除联系人编号为"' + Ids + '"的数据项?').then(function () {
      return delContact(Ids);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
   proxy.download("system/role/export", {
      ...queryParams.value,
   }, `role_${new Date().getTime()}.xlsx`);
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
   ids.value = selection.map(item => item.id);
   single.value = selection.length != 1;
   multiple.value = !selection.length;
}

/** 联系人状态修改 */
function handleStatusChange(row) {
   let text = row.status == '0' ? "启用" : "停用";
   proxy.$modal.confirm('确认要"' + text + '""' + row.contactsName + '"联系人吗?').then(function () {
      return statusContact(row.id, row.status);
   }).then(() => {
      proxy.$modal.msgSuccess(text + "成功");
   }).catch(function () {
      row.status = row.status == '0' ? '1' : '0';
   });
}

/** 重置新增的表单以及其他数据  */
function reset() {
   if (menuRef.value != undefined) {
      menuRef.value.setCheckedKeys([]);
   }
   menuExpand.value = false;
   menuNodeAll.value = false;
   deptExpand.value = true;
   deptNodeAll.value = false;
   form.value = {
      id: undefined,
      coutactsName: undefined,
      status: '0',
   };
   proxy.resetForm("roleRef");
}

/** 添加联系人 */
function handleAdd() {
   reset();
   open.value = true;
   title.value = "添加联系人";
}

/** 修改联系人 */
function handleUpdate(row) {
   reset();
   getContact(row.id).then((res) => {
      console.log('联系人详情', res)
      form.value = res.data;
      open.value = true;
   }).catch(() => {
      form.value = row;
      open.value = true;
   })
   title.value = "修改联系人";
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
         if (form.value.id != undefined) {
            updateContact(form.value).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               getList();
            });
         } else {
            addContact(form.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}

/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
getDeptTree();
getList();
</script>
